package com.van.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.van.Service.MenuService;
import com.van.Service.SysLogService;
import com.van.entity.Menu;
import com.van.entity.ResPonObject;
import com.van.entity.SysLog;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author VanKa qq:2395073039
 * @date 2021/6/11 10:16
 */
@Controller
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private MenuService menuService;

    /**
     * 获取导航列表
     * 整理后的
     */
    @ResponseBody
    @RequestMapping("/list")
    public ResPonObject list() {

        List<Menu> list = menuService.organizeList(null);

        return new ResPonObject(list);
    }



    /**
     * 获取数据列表
     * @param keyword 模糊查询
     * @param page 页码
     * @param type 类型 0 全部 1父类 2子类
     * @param sizes 页面大小
     */
    @ResponseBody
    @RequestMapping("/getList")
    public ResPonObject getList(
            @RequestParam(name = "keyword", required = false, defaultValue = "") String keyword,
            @RequestParam(name = "type", required = false, defaultValue = "0") int type,
            @RequestParam(name = "page", required = false, defaultValue = "1") int page,
            @RequestParam(name = "limit", required = false, defaultValue = "10") int sizes) {
        //todo 判断权限

        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();

        if (!Strings.isNotEmpty(keyword)) {
            queryWrapper.like("name", keyword);
        }
        if (type != 0){
            queryWrapper.eq("type", type);
        }
//        queryWrapper.orderByDesc("createTime");

        IPage<Menu> menuPage = menuService.page(new Page<>(page, sizes), queryWrapper);

        return new ResPonObject((int) menuPage.getTotal(),menuPage.getRecords());
    }

    /**
     * 根据id获取对象
     * @param id id
     */
    @ResponseBody
    @RequestMapping("/getById")
    public ResPonObject getById(
            @RequestParam(name = "id", required = false, defaultValue = "0") int id
    ){
        //todo 判断权限
        if (id <= 0){
            return new ResPonObject("传递参数丢失，查询失败！", ResPonObject.Status.ERROR);
        }
        Menu byId = menuService.getById(id);

        return new ResPonObject((byId != null), byId,"查询数据为空");
    }

    /**
     * 添加
     */
    @ResponseBody
    @RequestMapping("/add")
    public ResPonObject add(
            @RequestParam(name = "name", required = false, defaultValue = "") String name,
            @RequestParam(name = "type", required = false, defaultValue = "0") int type,
            @RequestParam(name = "sId", required = false, defaultValue = "0") int sId,
            @RequestParam(name = "url", required = false, defaultValue = "") String url,
            @RequestParam(name = "icon", required = false, defaultValue = "") String icon,
            @RequestParam(name = "sort", required = false, defaultValue = "1") int sort
    ) {
        //todo 判断权限
        String sName = "系统";
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();

        if (Strings.isEmpty(name)){
            return new ResPonObject("请输入标题！", ResPonObject.Status.ERROR);
        }else {
            queryWrapper.eq("name", name);
        }
        Menu m = menuService.getOneData(queryWrapper);
        if (m != null){
            return new ResPonObject("标题重复！", ResPonObject.Status.ERROR);
        }
        if (sId > 0){
            Menu byId = menuService.getById(sId);
            if (byId == null){
                return new ResPonObject("父导航不存在！", ResPonObject.Status.ERROR);
            }
            sName = byId.getName();
        }
        Menu menu = new Menu();
        menu.setName(name);
        menu.setType(type);
        menu.setSId(sId);
        menu.setSName(sName);
        menu.setUrl(url);
        menu.setIcon(icon);
        menu.setSort(sort);

        boolean save = menuService.save(menu);

        sysLogService.save(new SysLog(SysLog.Status.Add_Menu,"用户[xxx]" + "添加导航" + menu.getName() ,menu,null));

        return new ResPonObject(save, menu,"添加失败！");
    }
    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    public ResPonObject update(
            @RequestParam(name = "id", required = false, defaultValue = "0") int id,
            @RequestParam(name = "name", required = false, defaultValue = "") String name,
            @RequestParam(name = "type", required = false, defaultValue = "0") int type,
            @RequestParam(name = "sId", required = false, defaultValue = "0") int sId,
            @RequestParam(name = "url", required = false, defaultValue = "") String url,
            @RequestParam(name = "icon", required = false, defaultValue = "") String icon,
            @RequestParam(name = "sort", required = false, defaultValue = "1") int sort
    ) {
        //todo 判断权限
        String sName = "系统";
        Menu menu = menuService.getById(id);
        if (menu == null){
            return new ResPonObject("数据不存在！", ResPonObject.Status.ERROR);
        }

        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        //todo 参数判断
        if (Strings.isEmpty(name)){
            return new ResPonObject("请输入标题！", ResPonObject.Status.ERROR);
        }else {
            queryWrapper.eq("name", name);
        }
        List<Menu> list = menuService.list(queryWrapper);

        if (list.size() == 0){

        }else if (list.size() == 1){
            if (list.get(0).getId() != id){
                return new ResPonObject("标题重复！", ResPonObject.Status.ERROR);
            }
        }else {
            return new ResPonObject("标题重复！", ResPonObject.Status.ERROR);
        }

        if (sId > 0){
            Menu byId = menuService.getById(sId);
            if (byId == null){
                return new ResPonObject("父导航不存在！", ResPonObject.Status.ERROR);
            }
            sName = byId.getName();
        }

        menu.setName(name);
        menu.setType(type);
        menu.setSId(sId);
        menu.setSName(sName);
        menu.setUrl(url);
        menu.setIcon(icon);
        menu.setSort(sort);

        boolean save = menuService.updateById(menu);

        sysLogService.save(new SysLog(SysLog.Status.Update_Menu,"用户[xxx]" + "修改导航" + menu.getName() ,menu,null));
        return new ResPonObject(save, menu,"修改失败！");

    }

    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping("/del")
    public ResPonObject del(@RequestParam("id") int id) {
        //todo 判断权限
        if (id <= 0){
            return new ResPonObject("传递参数丢失，删除失败！", ResPonObject.Status.ERROR);
        }
        Menu byId = menuService.getById(id);
        boolean on = menuService.removeById(id);

        sysLogService.save(new SysLog(SysLog.Status.Del_Menu,"用户[xxx]" + "删除导航" + byId.getName() ,byId,null));

        return new ResPonObject(on, null,"删除失败！");
    }

    /**
     * 批量删除
     */
    @ResponseBody
    @RequestMapping("/dels")
    public ResPonObject dels(@RequestParam("id[]") int[] ids) {
        boolean on = false;
        String msg = "", err = "", suc = "";

        //todo 判断权限
        if (ids.length > 0){
            for (int i : ids){
                boolean b = menuService.removeById(i);
                if (b){
                    suc += " [" + i + "] ";
                }else {
                    on = true;
                    err += " [" + i + "] ";
                }
            }

            msg = (err.length() > 0 ? "删除导航" + err +"（编号）失败！\n" :"") + (suc.length() >0 ? "删除导航" + suc +"（编号）成功！" :"");


            sysLogService.save(new SysLog(SysLog.Status.Del_Menu,"用户[xxx]" + msg, msg,null));
            return new ResPonObject(!on, null,msg);
        }

        return new ResPonObject(false, null,"请选中数据");
    }
}
